from django.db.models import Count, Avg
from django.shortcuts import render

from django import http
# Create your views here.
from rest_framework.generics import ListCreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.comments.models import Comment
from apps.comments.serializers import TeacherCommentModelSerializer, ArticleCommentModelSerializer
from utils.my_permission import MyPermission
from utils.notifications import Notification
from utils.paginations import PageNum


class CommentsModelView(ListCreateAPIView):
    def get(self, request, *args, **kwargs):
        key = request.query_params.get(self.lookup_field)
        if self.lookup_field == 'teacher_id':
            queryset = self.get_queryset().filter(teacher_id=key)
        elif self.lookup_field == 'article_id':
            queryset = self.get_queryset().filter(article_id=key, parent_id=None)
        elif self.lookup_field == 'parent_id':
            queryset = self.get_queryset().filter(parent_id=key)
        else:
            return http.JsonResponse({'message': '错误请求'})
        queryset = self.filter_queryset(queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class TeacherCommentsModelView(CommentsModelView):
    queryset = Comment.objects.all().annotate(like_count_temp=Count('like_users')).annotate(
        rating_avg_temp=Avg('rating')).order_by('-like_count_temp', '-rating_avg_temp', '-create_time').all()
    serializer_class = TeacherCommentModelSerializer
    permission_classes = [MyPermission]
    pagination_class = PageNum
    lookup_field = 'teacher_id'


class ArticleCommentsModelView(CommentsModelView):
    queryset = Comment.objects.all().annotate(like_count_temp=Count('like_users')).annotate(
        replies_count_temp=Count('replies')).order_by('-like_count_temp', '-replies_count_temp', '-create_time').all()
    serializer_class = ArticleCommentModelSerializer
    permission_classes = [MyPermission]
    pagination_class = PageNum
    lookup_field = 'article_id'


class ArticleCommentsRepliesModelView(CommentsModelView):
    queryset = Comment.objects.all().annotate(like_count_temp=Count('like_users')).order_by('-like_count_temp',
                                                                                            '-create_time').all()
    serializer_class = ArticleCommentModelSerializer
    permission_classes = [MyPermission]
    pagination_class = PageNum
    lookup_field = 'parent_id'


class LikeCommentView(APIView):

    def post(self, request, target):
        try:
            comment_target = Comment.objects.get(id=target)
            comment_target.like_users.add(request.user)
            comment_target.save()
            # 发送收藏通知
            Notification('点赞', request.user, comment_target.user, comment_target).send_system_message()
        except Exception as e:
            print(e)
            return http.JsonResponse({'message': '点赞失败'})
        return http.JsonResponse({'message': 'OK'})

    def delete(self, request, target):
        try:
            Comment.objects.get(id=target).like_users.remove(request.user)
        except Exception as e:
            print(e)
            return http.JsonResponse({'message': '取消点赞失败'})
        return http.JsonResponse({'message': 'OK'})
